<template>
    <div>
        <!-- 1. 导航部分 -->
        <el-breadcrumb separator-class="el-icon-arrow-right">
            <el-breadcrumb-item :to="{ path: '/' }">首页</el-breadcrumb-item>
            <el-breadcrumb-item>用户管理</el-breadcrumb-item>
            <el-breadcrumb-item>用户列表</el-breadcrumb-item>
        </el-breadcrumb>
        <br>
        <!-- 2.主体部分  -->
        <el-card>
            <el-row :gutter="20">
                <el-col :span="8">
                    <el-input placeholder="请输入内容" v-model="userInfo.query" clearable @clear="getUsers">
                        <el-button slot="append" icon="el-icon-search" @click="getUsers"></el-button>
                    </el-input>
                </el-col>
                <el-col :span="4">
                    <el-button type="primary" @click="addFormVisible = true">添加用户</el-button>
                </el-col>
            </el-row>
            <br>
            <!-- 表格展示 -->
            <el-table :data="users" stripe border style="width: 100%">
                <el-table-column type="index" label="#"></el-table-column>
                <el-table-column prop="username" label="姓名"></el-table-column>
                <el-table-column prop="email" label="邮箱"></el-table-column>
                <el-table-column prop="mobile" label="电话"></el-table-column>
                <el-table-column prop="role_name" label="角色"></el-table-column>
                <el-table-column label="状态">
                    <template v-slot="{ row }">
                        <el-switch v-model="row.mg_state" @change="changeState(row)"></el-switch>
                    </template>
                </el-table-column>
                <el-table-column label="操作" v-slot="{ row }">
                    <!-- v-slot="{row}" -->
                    <el-button size="mini" type="primary" icon="el-icon-edit" @click="showEditDialog(row)"></el-button>
                    <el-button size="mini" type="danger" @click="delUsers(row.id)" icon="el-icon-delete"></el-button>
                    <el-button size="mini" type="warning" @click='setRolesHandle(row)' icon="el-icon-setting"></el-button>
                </el-table-column>

            </el-table>
            <br>
            <!-- 分页功能 -->
            <el-pagination @size-change="handleSizeChange" @current-change="handleCurrentChange"
                :current-page="userInfo.pagenum" :page-sizes="[1, 2, 3, 5, 10]" :page-size="userInfo.pagesize"
                layout="total, sizes, prev, pager, next, jumper" :total="total">
            </el-pagination>
        </el-card>

        <!-- 3. 添加用户的弹框 -->
        <!-- dialogFormVisible 布尔值 真则 显示 假则 隐藏 -->
        <!-- form 关联数据 -->
        <el-dialog title="添加用户" :visible.sync="addFormVisible" width="50%">
            <el-form :model="addUsersForm" label-width="70px" :rules="addRules" ref="addUsersForm">
                <el-form-item label="用户名" prop="username">
                    <el-input v-model="addUsersForm.username" autocomplete="off"></el-input>
                </el-form-item>
                <el-form-item label="密码" prop="password">
                    <el-input v-model="addUsersForm.password" autocomplete="off" type="password"></el-input>
                </el-form-item>
                <el-form-item label="邮箱" prop="email">
                    <el-input v-model="addUsersForm.email" autocomplete="off"></el-input>
                </el-form-item>
                <el-form-item label="手机" prop="mobile">
                    <el-input v-model="addUsersForm.mobile" autocomplete="off"></el-input>
                </el-form-item>
            </el-form>
            <div slot="footer" class="dialog-footer">
                <el-button @click="cancelAdd">取 消</el-button>
                <el-button type="primary" @click="confirmAdd">确 定</el-button>
            </div>
        </el-dialog>


        <!-- 修改信息 -->
        <el-dialog title="修改用户" :visible.sync="editFormVisible" width="50%">
            <el-form :model="editUsersForm" label-width="70px" :rules="editRules" ref="editUsersForm">
                <el-form-item label="用户名">
                    <el-input v-model="editUsersForm.username" autocomplete="off" disabled></el-input>
                </el-form-item>
                <el-form-item label="邮箱" prop="email">
                    <el-input v-model="editUsersForm.email" autocomplete="off"></el-input>
                </el-form-item>
                <el-form-item label="手机" prop="mobile">
                    <el-input v-model="editUsersForm.mobile" autocomplete="off"></el-input>
                </el-form-item>
            </el-form>
            <div slot="footer" class="dialog-footer">
                <el-button @click="editFormVisible = false">取 消</el-button>
                <el-button type="primary" @click="confirmEdit">确 定</el-button>
            </div>
        </el-dialog>

        <!-- 分配角色 -->
        <el-dialog title="分配角色" :visible.sync="setRoleVisible" width="50%">
            <el-form :model="setRolesForm" label-width="70px">
                <p>当前用户名：{{ setRolesForm.username }}</p>
                <p>当前的角色：{{ setRolesForm.role_name }}</p>
                <p>分配角色：<el-select v-model="value" placeholder="请选择">
                        <el-option v-for="item in options" :key="item.id" 
                            :label="item.roleName" :value="item.id">
                        </el-option>
                    </el-select>
                </p>
            </el-form>
            <div slot="footer" class="dialog-footer">
                <el-button>取 消</el-button>
                <el-button type="primary">确 定</el-button>
            </div>
        </el-dialog>

    </div>
</template>
<script>
import { getUsers, addUser, putState, editUsers, delUsers  ,getRoles} from '@/api/users.js'
export default {
    name: "users-com",
    data() {
        const checkEmail = (rule, val, cb) => {
            //   rule 校验对象  // val 输入内容// cb 回调函数
            let reg = /^\w+\@\w+\.(com|cn|net)$/ // 1212@163.com
            if (reg.test(val)) {
                return cb()
            }
            cb(new Error("邮箱格式不正确!"))
        }
        // checkMobile
        const checkMobile = (rule, val, cb) => {
            //   rule 校验对象  // val 输入内容// cb 回调函数
            let reg = /^1[3-9]\d{9}$/ // 1212@163.com
            if (reg.test(val)) {
                return cb()
            }
            cb(new Error("手机号码不正确!"))
        }
        return {
            userInfo: {
                query: "",//搜索内容
                pagenum: 1,//页码
                pagesize: 3 // 每页显示条数
            },
            total: 0,//数据总条数
            users: [], //请求到的数据
            addUsersForm: {
                username: "",
                password: "",
                email: "",
                mobile: ""
            },
            addFormVisible: false,
            addRules: {
                username: [{ required: true, message: "必填项!", triggle: "blur" },
                { min: 3, max: 6, message: "格式不正确", triggle: "blur" }],
                password: [{ required: true, message: "必填项!", triggle: "blur" },
                { min: 6, max: 12, message: "格式不正确", triggle: "blur" }],
                email: [{ required: true, message: "必填项!", triggle: "blur" }, {
                    validator: checkEmail, triggle: "blur"
                }],
                mobile: [{ required: true, message: "必填项!", triggle: "blur" }, {
                    validator: checkMobile, triggle: "blur"
                }]
            },
            // -----------------------
            editFormVisible: false,// 编辑弹框的切换
            editUsersForm: {},
            editRules: {
                email: [{ required: true, message: "必填项!", triggle: "blur" }, {
                    validator: checkEmail, triggle: "blur"
                }],
                mobile: [{ required: true, message: "必填项!", triggle: "blur" }, {
                    validator: checkMobile, triggle: "blur"
                }]
            },
            // 设置角色部分
            setRoleVisible: false,
            setRolesForm: {},
            options: [],
            value: ''
        }
    },
    created() {
        this.getUsers()
    },
    methods: {
        async getUsers() {
            //    1.请求数据
            let { data: { data, meta } } = await getUsers(this.userInfo)
            // 2. 判断是否成功
            if (meta.status != 200) return this.$message("用户列表请求失败!")
            // 3.赋值
            this.total = data.total // 总数据条数
            this.users = data.users //请求到的数据
        },
        // 修改每一页的条数的时候 触发
        handleSizeChange(size) {
            this.userInfo.pagesize = size
            this.getUsers()
            // console.log('size',size);
        },
        // 修改页码的时候触发
        handleCurrentChange(num) {
            this.userInfo.pagenum = num;
            this.getUsers()
            // console.log('num' , num);
        },
        // 点击添加用户的取消按钮
        cancelAdd() {
            // 重置表单
            this.$refs.addUsersForm.resetFields()
            // 关闭 弹框
            this.addFormVisible = false
        },
        // 点击 添加用户的 确定按钮
        confirmAdd() {
            // isOk 都校验成功 则 true  有一个不成功则 false 
            this.$refs.addUsersForm.validate(async (isOk) => {
                // 1. 如果表单校验失败 则 弹出提示
                if (!isOk) return this.$message("表单校验失败!");
                // 2.发送请求
                let { data: { data, meta } } = await addUser(this.addUsersForm)
                // 3.判断
                if (meta.status != 201) return this.$message.fail("添加用户失败!")
                // 4. 弹出提示
                this.$message.success("添加成功!")
                //5. 取消弹框
                this.addFormVisible = false
                // 6. 更新数据
                this.getUsers()
            })


        },
        async changeState(row) {
            // 1 .发送数据
            let { data: { meta } } = await putState(row.id, row.mg_state)
            // 2. 如果发送失败则 ...
            if (meta.status != 200) return this.$message.error("状态修改失败!")
            // 3.发送成功则弹出提示 ;
            this.$message.success(meta.msg)
        },
        // 点击 编辑按钮 触发
        showEditDialog(row) {
            // 
            this.editUsersForm = { ...row };
            this.editFormVisible = true
        },
        // 点击编辑框的确认按钮 
        async confirmEdit() {
            // 1. 发送请求
            let { data: { meta } } = await editUsers(this.editUsersForm)
            // 2.如果请求失败
            if (meta.status != 200) return this.$message.error("修改请求失败!")
            // 3.成功
            this.$message.success(meta.msg)
            // 4. 关闭弹框
            this.editFormVisible = false
            // 5. 刷新数据
            this.getUsers()
        },
        // 点击删除按钮
        async delUsers(id) {
            let str = await this.$confirm('此操作将永久删除用户信息, 是否继续?', '提示', {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                type: 'warning'
            }).catch(err => err)
            if (str == 'cancel') return this.$message.info("您取消了删除")
            // 发起请求
            let { data: { meta } } = await delUsers(id)
            // 如果失败
            if (meta.status != 200) return this.$message.error("您删除失败!")
            // 删除成功
            this.$message.success("删除成功!")
            // 更新数据
            this.getUsers()
        },
        // 当点击设置角色的时候   setRolesForm:{} 
        async setRolesHandle(row) {
            this.setRolesForm = { ...row }
            this.setRoleVisible = true;//显示弹框
            // 发起请求
            let {data:{data,meta}} = await getRoles()
            if(meta.status!=200) return this.$message("请求失败")
           this.options = data;
        }
    }
}
</script>
<style lang="scss" scoped>
::v-deep .el-breadcrumb__inner {
    font-size: 12px;
}
</style>